package com.puzzlebazar.client.squaregrid.view;

import com.google.gwt.user.client.ui.Composite;
import com.puzzlebazar.client.util.Recti;
import com.puzzlebazar.client.util.Vec2i;


public abstract class CompositeView extends Composite {

	protected final Vec2i gridSize = new Vec2i();
	protected final Recti innerRect = new Recti();
	
	/**
	 * Provides subclasses access to the parent view that defines this
	 * composite.
	 * 
	 * @return the view
	 */
	protected SGView getView() {
		if( !( getParent() instanceof SGView ) ) return null;
		return (SGView)getParent();
	}

	@Override
	public void setWidth(String width) {
		super.setWidth(width);
		checkCellChange();
	}

	@Override
	public void setHeight(String height) {
		super.setHeight(height);
		checkCellChange();
	}

	/**
	 * Check if any cell has changed its location or size and if so notify the object
	 */
	private void checkCellChange() {
		SGView view = getView();
		if( view == null ) return;
		boolean changed = false;
		Recti newInnerRect = view.getInnerRect();
		if( !innerRect.equals(newInnerRect) ) {
			innerRect.copy( newInnerRect );
			changed = true;
		}
		Vec2i newGridSize = view.getGridSize();
		if( !gridSize.equals(newInnerRect) ) {
			gridSize.copy( newGridSize );
			changed = true;
		}
		if( changed ) notifyCellChanged();
	}
	

	/**
	 * Called whenever any cell has changed its location or size
	 */
	abstract protected void notifyCellChanged();
}
